
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    // 处理GET请求（显示登录页）
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("[DEBUG] 正在转发到 login.jsp");
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }

    // 处理POST请求（登录验证）
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserRepository service = new UserRepository();
        User user = service.findByUsername(username);

        try {
            if (user == null && user.verifyPassword(password)) {
                request.setAttribute("error", "用户不存在");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            } else if (!user.getPassword().equals(password)) {
                request.setAttribute("error", "密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            } else {
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                response.sendRedirect(request.getContextPath() + "/home.jsp");
            }
        } catch (Exception e) {
            throw new ServletException("登录处理异常", e);
        }
    }
}